<?php
include_once "txtviewer_design.php";

// gets the filename without extension
if (preg_match('/(.*)[.].*/', $_GET['file'], $regs_ext))	
    print_header($regs_ext[1]);
else
	print_header("Home");

// loads the text file
$subject = file_get_contents($_GET['file']);

// separates the titles from contents like as in "[Some title]\nFree content\nFree text" pairs
preg_match_all('/\\[(.*)\\]|(.*)/', $subject, $result, PREG_SET_ORDER);

foreach($result as $i) {
    $title = $i[1];
    $content = $i[2];

    if (strlen($title) > 0) {
        // prints the title to html
        echo "<a name='$title'><h2>$title</h2></a>";
        
        // adds the current title to an array of titles, for later usage in sidebar
        $titles_array[] = $title;
    }
    
    if (strlen($content) > 0) {
        // separates text in "Name: text" pairs
        preg_match_all('/(?:([^ ]+): )?(.*)/', $content, $content_result);
        
        for ($j = 0; $j < count($content_result[0]); $j++) {
            if (strlen($content_result[1][$j]) > 0)
                // prints the "name" to html
                echo '<h4>'.$content_result[1][$j].'</h4>';
                
            if (strlen($content_result[2][$j]) > 0)
            {
                // make link urls and then prints the content to html
                $res = preg_replace('/\\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]/i', '<a href="\\0" target="_blank">\\0</a>', $content_result[2][$j]);
                
                // puts in bold prices in u$s and other currencies
                // note: pcre doesn't supports unicode chars
                // $res = preg_replace('/(u\\$s|[\\$\\u00A3\\u00A5\\uFFE1\\uFFE5\\uFFE6\\u20AC]) ?([+-~.\\d]+)/', '<strong>\\1 \\2</strong>', $res);
                // $res = preg_replace('/(u\\$s|\\$) ?([+-~.\\d]+)/', '<strong>\\1 \\2</strong>', $res);

                // puts in bold text surrounded by *text*
                $res = preg_replace('/( |\\r\\n)[*](.*)[*]( |\\r\\n)/', '\\1<b>\\2</b>\\3', $res);
                
                // puts in italic text surrounded by _text_
                $res = preg_replace('/( |\\r\\n)[_](.*)[_]( |\\r\\n)/', '\\1<i>\\2</i>\\3', $res);

                echo $res;
            }
        }
        
        echo '<br />';
    }
}

print_sidebar();

// prints the links in the sidebar
foreach($titles_array as $title)
    echo "<li><a href='#$title'>$title</a></li>";

print_footer();
?>
